package controller;

import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import manager.UserManager;
import remoteEntity.User;

/**
 * UserController
 *
 * JSF Managed backing bean containing user state in a session. Behind the
 * scenes the user is hold within a stateful UserManager EJB.
 */
@ManagedBean
@SessionScoped
public class UserController implements Serializable {

    @EJB
    private UserManager userManager;

    public User getUser() {
        return userManager.getUser();
    }

    public void setUser(User user) {
        userManager.setUser(user);
    }

    public String tryLogin() {
        try {
            System.out.println("controller attempting login for user "+getUser().getUsername());
            userManager.login();

            //faces-redirect makes the URI change
            return "pretty:browse";
        } catch (Exception e) {
            FacesMessage msg = new FacesMessage("Wrong username and/or password!");
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            FacesContext.getCurrentInstance().addMessage(null, msg);

            return "";
        }
    }

    /**
     * Destoroys the curret session.
     *
     * @return
     */
    public String logout() {
        //do we need to do this?
        //loggedIn = false;
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "pretty:browse";
    }

    public String attemptRegister() {
        try {
            userManager.register();
            return "pretty:browse";
        } catch (Exception e) {
            //TODO: better error handling
            FacesMessage msg = new FacesMessage("Username taken.");
            msg.setSeverity(FacesMessage.SEVERITY_WARN);
            FacesContext.getCurrentInstance().addMessage(null, msg);

            return "";
        }
    }

    public boolean isLoggedIn() {
        return userManager.getLoggedIn();
    }
    
    public boolean getLoggedIn() {
        return userManager.getLoggedIn();
    }

    public void setLoggedIn(boolean loggedIn) {
        userManager.setLoggedIn(loggedIn);
    }

    public boolean getIsAdmin() {
        return userManager.getIsAdmin();
    }

    public User getUserById(int id) {
        return userManager.getUserById(id);
    }

    /**
     * Creates a new instance of LoginBean
     */
    public UserController() {
    }
}
